//
//  PhotoBrowserCell.swift
//  weibo
//
//  Created by sanya on 15/7/3.
//  Copyright © 2015年 sanya. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage
import SVProgressHUD
protocol photoBrowserCellDelegate:NSObjectProtocol {
    func PhotoBrowserCellDidTapImage()
}


class PhotoBrowserCell: UICollectionViewCell,UIScrollViewDelegate {
    weak var photoDelegaet:photoBrowserCellDelegate?
    var imageURL:NSURL? {
        
        didSet{
            indicator.startAnimating()
            resetScrollView()
            imageIVew.sd_setImageWithURL(imageURL, placeholderImage: nil) { (image, error, _, _)  in
                if error != nil{
                    SVProgressHUD.showErrorWithStatus("你的网速不给力")
                    return
                }
                // 下载完成之后，自动设置图像的尺寸
                self.indicator.stopAnimating()
                self.imagePosition(image)
            }
        }
    }
    /// 重设scrollView 的参数
    private func resetScrollView() {
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    /// 代理方法
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageIVew
    }
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        // 重新计算位置
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        if offsetX < 0 {
            offsetX = 0
        }
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        if offsetY < 0{
            offsetY = 0
        }
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
    }
    /// 设置位置
    private func imagePosition(image:UIImage) {
        // 计算 y 值
        let size = displaySize(image)
        // 判断是否是长图
        if size.height > bounds.height {
            imageIVew.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentSize = size
        }else{
            // 短图
            let y = (bounds.height - size.height) * 0.5
            imageIVew.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
        }
    }
    private func displaySize(image:UIImage) -> CGSize {
        let scale = image.size.height / image.size.width
        let h = scale * bounds.width
        return CGSize(width: bounds.width, height: h)
    }

    // frame 已经有正确的数值！是因为之前 layout 已经设置过 itemSize
    override init(frame: CGRect) {
        super.init(frame: frame)
//        print(NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true))

        scrollView.frame = bounds
        addSubview(scrollView)
        scrollView.addSubview(imageIVew)
        addSubview(indicator)
        indicator.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: nil)
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2
        scrollView.delegate = self
        imageIVew.userInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: "closeImage")
        imageIVew.addGestureRecognizer(tap)
    }
    func closeImage() {
        photoDelegaet?.PhotoBrowserCellDidTapImage()
        
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private lazy var scrollView = UIScrollView()
    lazy var imageIVew = UIImageView()
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
}
